<template>
	<view class="container">
		<!-- 学生信息 -->
		<view class="student-info">
			<view class="student-details">
				<text class="student-name">姓名: {{ student.name || '未知学生' }}</text>
				<text class="student-id">班级: {{ student.student_class || '未知班级' }}</text>
				<text class="student-id">学号: {{ student.student_id || '未知学号' }}</text>
				<!-- <text style="font-size: 18px;color: #666;margin-left: 30rpx;" @click="GoAll()">Go</text> -->
			</view>
			<u-icon name="download" color="#2979ff" size="28" @click="saveImage()"></u-icon>
		</view>

		<view style="height: 750rpx; position: relative">
			<l-echart ref="chartRef" @finished="init">
			</l-echart>

		</view>
		<!-- 用来显示图片的地方 -->
		<!-- <image :src="imagePath" mode="aspectFit"></image> -->
		<canvas canvas-id="scoreCanvas" :style="{ 
        width: canvasWidth + 'px', 
        height: canvasHeight + 'px',
        position: 'absolute',
        left: '-9999px'  // 隐藏画布
        }"></canvas>
		<!-- 学生每周成绩和排名的表格 -->
		<view class="table-container">
			<table class="score-table">
				<thead>
					<tr>
						<th>周数</th>
						<th>分数</th>
						<th>分变化</th>
						<th>班排名</th>
						<th>名变化</th>
						<th>级排名</th>
						<th>名变化</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="week in weeks" :key="'detail-' + week">
						<!-- <td>第{{ week }}周</td> -->
						<td style="font-weight: 700;">{{ week }}</td>
						<td>{{ getScore(student.weeks, week) }}</td>
						<td>
							<span v-if="getScoreChange(week) < 0" style="color: #67C23A;">
								↓{{ Math.abs(getScoreChange(week)) }}</span>
							<span v-else-if="getScoreChange(week) > 0" style="color: red;">↑
								{{ Math.abs(getScoreChange(week)) }}</span>
							<span v-else>{{ getScoreChange(week) }}</span>
						</td>
						<td>{{ getRanking(student.weeks, week) }}</td>
						<td>
							<span v-if="getRankingChange(week) < 0" style="color: red;">↑
								{{ Math.abs(getRankingChange(week)) }}</span>
							<span v-else-if="getRankingChange(week) > 0" style="color: #67C23A;">↓
								{{ Math.abs(getRankingChange(week)) }}</span>
							<span v-else>{{ getRankingChange(week) }}</span>
						</td>
						<td>{{ getGradeRanking(student.weeks, week) }}</td>
						<td>
							<span v-if="getGradeRankingChange(week) < 0" style="color: red;">↑
								{{ Math.abs(getGradeRankingChange(week)) }}</span>
							<span v-else-if="getGradeRankingChange(week) > 0" style="color: #67C23A;">↓
								{{ Math.abs(getGradeRankingChange(week)) }}</span>
							<span v-else>{{ getGradeRankingChange(week) }}</span>
						</td>

					</tr>
				</tbody>
			</table>
		</view>
	</view>
</template>


<style scoped>
	.container {
		padding: 20px;
		background-color: #f8f9fa;
		border-radius: 10px;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
	}

	.student-info {
		margin-bottom: 20px;
		padding: 15px;
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		display: flex;
		align-items: center;
		/* 垂直居中 */
		justify-content: space-between;
		/* 水平分布 */
	}

	.student-details {
		display: flex;
		align-items: center;
		/* 垂直居中 */
	}

	.student-name {
		font-size: 18px;
		font-weight: bold;
		color: #333;
	}

	.student-id {
		font-size: 14px;
		color: #666;
		margin-left: 10px;
	}

	.table-container {
		margin-top: 20px;
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
		overflow-x: auto;
		/* 支持横向滚动 */
	}

	.score-table {
		width: 100%;
		border-collapse: collapse;
		text-align: center;
	}

	.score-table th,
	.score-table td {
		padding: 12px;
		border: 1px solid #e4e7ed;
	}

	.score-table th {
		background-color: #f8f9fa;
		font-weight: bold;
		color: #333;
	}

	.score-table tbody tr:nth-child(even) {
		background-color: #f8f9fa;
	}

	.score-table tbody tr:hover {
		background-color: #e9ecef;
	}
</style>

<script>
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min'
	export default {
		data() {
			return {
				canvasWidth: 600, // 根据实际内容宽度调整
				canvasHeight: 400, // 根据行数动态计算
				student: {},
				weeks: [],
				dynamicTitle: '学生每周成绩变化', // 这里是初始的动态标题
				imagePath: '', // 用来存储保存后的图片路径
				chart: null // 存储图表实例
			};
		},
		onLoad(options) {
			if (options.name) {
				// 从本地缓存获取数据
				this.student = uni.getStorageSync(options.name + "年级版");
				this.weeks = uni.getStorageSync('周数年级版');
			} else {
				console.error("Failed to load parameters.");
			}
			// 假设你要在mounted生命周期中动态更新标题
			this.updateTitle();
		},
		methods: {
			updateTitle() {
				this.dynamicTitle = this.student.name + '成绩变化'; // 更新标题
			},
			GoAll() {
				uni.navigateTo({
					url: '/pages/index/gradeChart?name=' + this.student.name + "年级版",
					animationType: 'fade-in',
					animationDuration: 200
				});
			},
			async init() {
				// chart 图表实例不能存在data里
				this.chart = await this.$refs.chartRef.init(echarts);
				// 处理数据
				const xAxisData = this.weeks.map(week => week); // 横轴: 周数
				const scoreData = this.weeks.map(week => {
					const score = this.getScore(this.student.weeks, week);
					return score !== '-' ? score : 0; // 如果没有分数，则使用0
				});

				// 配置图表
				const option = {
					title: {
						text: this.dynamicTitle, // 动态绑定标题
						left: 'center'
					},
					tooltip: {
						trigger: 'axis'
					},
					xAxis: {
						type: 'category',
						data: xAxisData
					},
					yAxis: {
						type: 'value',
						name: '分数'
					},
					series: [{
						data: scoreData,
						type: 'line',
						lineStyle: {
							color: '#5470C6'
						},
						itemStyle: {
							color: '#5470C6'
						}
					}]
				};
				this.chart.setOption(option);
			},
			saveImage() {
				if (!this.chart) {
					return;
				}
				// 使用 canvasToTempFilePath 获取图片路径
				this.$refs.chartRef.canvasToTempFilePath({
					success: (res) => {
						// 获取临时文件路径
						const imagePath = res.tempFilePath;

						// 保存到相册
						uni.saveImageToPhotosAlbum({
							filePath: imagePath,
							success: () => {
								console.log('图片已保存到相册');
								this.exportTableToImage();
								// uni.showToast({
								// 	title: '删除成功',
								// 	icon: 'success'
								// });
							},
							fail: (err) => {
								console.error('保存图片到相册失败：', err);
							}
						});
					},
					fail: (err) => {
						console.error('保存图片失败：', err);
					}
				});
			},
			getScore(weeks, week) {
				const weekData = weeks.find(w => w.week === week);
				return weekData ? weekData.score : '-';
			},
			getRanking(weeks, week) {
				const weekData = weeks.find(w => w.week === week);
				return weekData ? weekData.class_ranking : '-';
			},
			getGradeRanking(weeks, week) {
				const weekData = weeks.find(w => w.week === week);
				return weekData ? weekData.grade_ranking : '-';
			},
			// 获取分数变化
			getScoreChange(week) {
				const currentWeekData = this.student.weeks.find((item) => item.week === week);
				if (!currentWeekData) return 0; // 如果当前周没有数据，返回 0

				// 找到当前周之前的最近一次有考试的数据
				let previousWeekData = null;
				for (let i = week - 1; i >= 1; i--) {
					previousWeekData = this.student.weeks.find((item) => item.week === i);
					if (previousWeekData) break; // 找到第一个有数据的周
				}

				if (!previousWeekData) {
					return '-'; // 如果找不到上一周有考试的数据，返回 '-'
				} else {
					return currentWeekData.score - previousWeekData.score; // 返回分数变化
				}
			},
			// 获取班级排名变化
			getRankingChange(week) {
				const currentWeekData = this.student.weeks.find((item) => item.week === week);
				if (!currentWeekData || currentWeekData.class_ranking === undefined) return '-'; // 如果当前周没有数据或没有排名，返回 '-'

				// 找到当前周之前的最近一次有排名的数据
				let previousWeekData = null;
				for (let i = week - 1; i >= 1; i--) {
					previousWeekData = this.student.weeks.find((item) => item.week === i && item.class_ranking !==
						undefined);
					if (previousWeekData) break; // 找到第一个有排名的数据周
				}

				if (!previousWeekData) {
					return '-'; // 如果找不到上一周有排名的数据，返回 '-'
				} else {
					return currentWeekData.class_ranking - previousWeekData.class_ranking; // 返回排名变化
				}
			},
			// 获取年级排名变化
			getGradeRankingChange(week) {
				const currentWeekData = this.student.weeks.find((item) => item.week === week);
				if (!currentWeekData || currentWeekData.grade_ranking === undefined) return '-'; // 如果当前周没有数据或没有排名，返回 '-'

				// 找到当前周之前的最近一次有排名的数据
				let previousWeekData = null;
				for (let i = week - 1; i >= 1; i--) {
					previousWeekData = this.student.weeks.find((item) => item.week === i && item.grade_ranking !==
						undefined);
					if (previousWeekData) break; // 找到第一个有排名的数据周
				}

				if (!previousWeekData) {
					return '-'; // 如果找不到上一周有排名的数据，返回 '-'
				} else {
					return currentWeekData.grade_ranking - previousWeekData.grade_ranking; // 返回排名变化
				}
			},
			// 动态计算画布高度
			calculateCanvasHeight() {
				const rowCount = this.weeks.length;
				this.canvasHeight = 40 + (rowCount * 40); // 表头40px + 每行40px
			},
			// 核心绘制方法
			async drawCanvasTable() {
			  const ctx = uni.createCanvasContext('scoreCanvas', this);
			  const { header, rows } = this.generateTableData();
			  
			  // 增加学生姓名栏高度
			  const studentNameHeight = 40;
			  
			  // 清空画布（需要确保canvasHeight已增加学生姓名栏高度）
			  ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
			
			  // 绘制学生姓名栏（新增部分）
			  ctx.setFillStyle('#409EFF'); // 使用显眼的蓝色背景
			  ctx.fillRect(0, 0, this.canvasWidth, studentNameHeight);
			  ctx.setFontSize(18);
			  ctx.setFillStyle('#fff'); // 白色文字
			  ctx.setTextAlign('center'); // 水平居中
			  ctx.setTextBaseline('middle'); // 垂直居中
			  ctx.fillText(
			    this.student.name || '学生成绩单', 
			    this.canvasWidth / 2, 
			    studentNameHeight / 2
			  );
			
			  // 调整原表头和数据行的绘制位置（整体下移）
			  const tableStartY = studentNameHeight; // 从学生姓名下方开始
			  
			  // 绘制表头（位置下移）
			  ctx.setFillStyle('#f0f0f0');
			  ctx.fillRect(0, tableStartY, this.canvasWidth, 40);
			  ctx.setFontSize(14);
			  ctx.setFillStyle('#333');
			  ctx.setTextAlign('left'); // 恢复左对齐
			  ctx.setTextBaseline('alphabetic');
			  const headers = ['周数', '分数', '分变化', '排名', '名变化'];
			  headers.forEach((text, index) => {
			    ctx.fillText(text, (this.canvasWidth / 5) * index + 10, tableStartY + 25);
			  });
			
			  // 绘制数据行（位置调整）
			  rows.forEach((row, rowIndex) => {
			    const yPos = tableStartY + 40 + (rowIndex * 40);
			    ctx.setFillStyle(rowIndex % 2 === 0 ? '#fff' : '#f9f9f9');
			    ctx.fillRect(0, yPos, this.canvasWidth, 40);
			
			    row.forEach((cell, colIndex) => {
			      ctx.setFillStyle(cell.color || '#666');
			      ctx.fillText(
			        cell.text,
			        (this.canvasWidth / 5) * colIndex + 10,
			        yPos + 25
			      );
			    });
			  });
			
			  // 绘制边框（位置调整）
			  ctx.setStrokeStyle('#ddd');
			  ctx.setLineWidth(1);
			  
			  // 水平线（包含学生姓名栏）
			  const totalRows = rows.length + 2; // 学生姓名栏+表头+数据行
			  const rowHeight = 40;
			  for (let i = 0; i <= totalRows; i++) {
			    const y = i * rowHeight;
			    ctx.moveTo(0, y);
			    ctx.lineTo(this.canvasWidth, y);
			  }
			  
			  // 垂直线
			  const colWidth = this.canvasWidth / header.length;
			  for (let i = 0; i <= header.length; i++) {
			    const x = i * colWidth;
			    ctx.moveTo(x, 0); // 从顶部开始
			    ctx.lineTo(x, totalRows * rowHeight);
			  }
			  ctx.stroke();
			
			  await ctx.draw();
			},
			// 生成 Canvas 所需的格式化数据
			generateTableData() {
				return {
					header: ['周数', '分数', '分变化', '排名', '名变化'],
					rows: this.weeks.map(week => ([{
							text: week
						}, // 周数
						{
							text: this.getScore(this.student.weeks, week)
						}, // 分数
						{ // 分变化
							text: this.formatChangeText(
								this.getScoreChange(week),
								'score'
							),
							color: this.getChangeColor(this.getScoreChange(week))
						},
						{
							text: this.getRanking(this.student.weeks, week)
						}, // 排名
						{ // 名变化
							text: this.formatChangeText(
								this.getRankingChange(week),
								'ranking'
							),
							color: this.getChangeColor(-this.getRankingChange(week))
						}
					]))
				};
			},
			// 格式化变化文本（添加箭头）
			// formatChangeText(value, type) {
			// 	if (value === 0) return '0';
			// 	let arrow = value > 0 ? '↑' : '↓';
			// 	// 排名变化逻辑取反（↑代表排名上升=数字变小）
			// 	if (type === 'ranking') arrow = value > 0 ? '↓' : '↑';
			// 	return `${arrow}${Math.abs(value)}`;
			// },
			formatChangeText(value, type) {
				if (value === 0 || isNaN(Number(value))) return '-'; // 如果值为0或不是有效数字，则返回'-'

				let arrow = value > 0 ? '↑' : '↓';
				// 排名变化逻辑取反（↑代表排名上升=数字变小）
				if (type === 'ranking') arrow = value > 0 ? '↓' : '↑';

				return `${arrow}${Math.abs(Number(value))}`; // 确保转换为数字以避免潜在的类型问题
			},

			// 获取变化颜色
			getChangeColor(value) {
				if (value > 0) return '#FF4444'; // 红色
				if (value < 0) return '#67C23A'; // 绿色
				return '#666'; // 默认
			},

			// 导出为图片
			async exportTableToImage() {
				this.calculateCanvasHeight();
				await this.drawCanvasTable();

				uni.canvasToTempFilePath({
					canvasId: 'scoreCanvas',
					success: (res) => {
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => uni.showToast({
								title: '保存成功'
							})
						});
					}
				});
			}

		}
	};
</script>